package com.bookocean.infrastructure.persistence.repository;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bookocean.application.exception.BusinessException;
import com.bookocean.application.exception.WeChatErrorCodeEnum;
import com.bookocean.domain.repository.BookLikeRepository;
import com.bookocean.infrastructure.persistence.mapper.BookLikeMapper;
import com.bookocean.infrastructure.persistence.po.BookLikePO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 书摘点赞仓储实现类
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class BookLikeRepositoryImpl implements BookLikeRepository {

    private final BookLikeMapper bookLikeMapper;

    @Override
    public boolean existsByQuoteIdAndUserId(Long quoteId, Long userId) {
        // 参数校验
        if (ObjectUtil.isEmpty(quoteId) || ObjectUtil.isEmpty(userId)) {
            log.warn("检查点赞状态失败，书摘ID或用户ID不能为空: quoteId={}, userId={}", quoteId, userId);
            return false;
        }

        try {
            LambdaQueryWrapper<BookLikePO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BookLikePO::getTargetType, 1)
                    .eq(BookLikePO::getTargetId, quoteId)
                    .eq(BookLikePO::getUserId, userId);

            Long count = bookLikeMapper.selectCount(queryWrapper);
            boolean exists = count != null && count > 0;
            log.debug("检查点赞状态: quoteId={}, userId={}, exists={}", quoteId, userId, exists);
            return exists;
        } catch (Exception e) {
            log.error("检查点赞状态失败: quoteId={}, userId={}, 错误: {}", quoteId, userId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Integer getLikeCount(Long quoteId) {
        // 参数校验
        if (ObjectUtil.isEmpty(quoteId)) {
            log.warn("获取点赞数量失败，书摘ID不能为空: quoteId={}", quoteId);
            return 0;
        }

        try {
            LambdaQueryWrapper<BookLikePO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BookLikePO::getTargetType, 1)
                    .eq(BookLikePO::getTargetId, quoteId);

            Long count = bookLikeMapper.selectCount(queryWrapper);
            Integer likeCount = count != null ? count.intValue() : 0;
            log.debug("获取点赞数量: quoteId={}, count={}", quoteId, likeCount);
            return likeCount;
        } catch (Exception e) {
            log.error("获取点赞数量失败: quoteId={}, 错误: {}", quoteId, e.getMessage(), e);
            return 0;
        }
    }

    // ========== 通用互动方法实现 ==========

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void like(Long targetId, Integer targetType, Long userId) {
        try {
            BookLikePO bookLikePO = new BookLikePO();
            bookLikePO.setTargetType(targetType);
            bookLikePO.setTargetId(targetId);
            bookLikePO.setUserId(userId);
            bookLikePO.setCreatedAt(LocalDateTime.now());

            int result = bookLikeMapper.insert(bookLikePO);
            if (result > 0) {
                log.info("创建点赞成功: targetId={}, targetType={}, userId={}", targetId, targetType, userId);
            } else {
                log.error("创建点赞失败，数据库插入返回0: targetId={}, targetType={}, userId={}", targetId, targetType, userId);
                throw new BusinessException(WeChatErrorCodeEnum.SYSTEM_ERROR);
            }
        } catch (DuplicateKeyException e) {
            log.warn("重复点赞，忽略操作: targetId={}, targetType={}, userId={}", targetId, targetType, userId);
        } catch (Exception e) {
            log.error("创建点赞失败: targetId={}, targetType={}, userId={}, 错误: {}", targetId, targetType, userId, e.getMessage(), e);
            throw new BusinessException(WeChatErrorCodeEnum.SYSTEM_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlike(Long targetId, Integer targetType, Long userId) {
        if (ObjectUtil.isEmpty(targetId) || ObjectUtil.isEmpty(targetType) || ObjectUtil.isEmpty(userId)) {
            log.warn("删除点赞失败，参数不能为空: targetId={}, targetType={}, userId={}", targetId, targetType, userId);
            throw new BusinessException(WeChatErrorCodeEnum.PARAM_ERROR);
        }

        try {
            LambdaQueryWrapper<BookLikePO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BookLikePO::getTargetType, targetType)
                    .eq(BookLikePO::getTargetId, targetId)
                    .eq(BookLikePO::getUserId, userId);

            int result = bookLikeMapper.delete(queryWrapper);
            if (result > 0) {
                log.info("删除点赞成功: targetId={}, targetType={}, userId={}", targetId, targetType, userId);
            } else {
                log.warn("删除点赞失败，未找到对应记录: targetId={}, targetType={}, userId={}", targetId, targetType, userId);
            }
        } catch (Exception e) {
            log.error("删除点赞失败: targetId={}, targetType={}, userId={}, 错误: {}", targetId, targetType, userId, e.getMessage(), e);
            throw new BusinessException(WeChatErrorCodeEnum.SYSTEM_ERROR);
        }
    }

    @Override
    public boolean isLikedByUser(Long targetId, Integer targetType, Long userId) {
        if (ObjectUtil.isEmpty(targetId) || ObjectUtil.isEmpty(targetType) || ObjectUtil.isEmpty(userId)) {
            log.warn("检查点赞状态失败，参数不能为空: targetId={}, targetType={}, userId={}", targetId, targetType, userId);
            return false;
        }

        try {
            LambdaQueryWrapper<BookLikePO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BookLikePO::getTargetType, targetType)
                    .eq(BookLikePO::getTargetId, targetId)
                    .eq(BookLikePO::getUserId, userId);

            Long count = bookLikeMapper.selectCount(queryWrapper);
            boolean exists = count != null && count > 0;
            log.debug("检查点赞状态: targetId={}, targetType={}, userId={}, exists={}", targetId, targetType, userId, exists);
            return exists;
        } catch (Exception e) {
            log.error("检查点赞状态失败: targetId={}, targetType={}, userId={}, 错误: {}", targetId, targetType, userId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Integer countByTarget(Long targetId, Integer targetType) {
        if (ObjectUtil.isEmpty(targetId) || ObjectUtil.isEmpty(targetType)) {
            log.warn("获取点赞数量失败，参数不能为空: targetId={}, targetType={}", targetId, targetType);
            return 0;
        }

        try {
            LambdaQueryWrapper<BookLikePO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BookLikePO::getTargetType, targetType)
                    .eq(BookLikePO::getTargetId, targetId);

            Long count = bookLikeMapper.selectCount(queryWrapper);
            Integer likeCount = count != null ? count.intValue() : 0;
            log.debug("获取点赞数量: targetId={}, targetType={}, count={}", targetId, targetType, likeCount);
            return likeCount;
        } catch (Exception e) {
            log.error("获取点赞数量失败: targetId={}, targetType={}, 错误: {}", targetId, targetType, e.getMessage(), e);
            return 0;
        }
    }
}
